package com.telnetnz.ticketdesk.bean.misc;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

import org.apache.log4j.Logger;

import com.telnetnz.ticketdesk.dao.entity.TemplateEntity;
import com.telnetnz.ticketdesk.dao.wrapper.TemplateWrap;

import freemarker.cache.TemplateLoader;

public class DatabaseTemplateLoader implements TemplateLoader 
{
	private static Logger logger = Logger.getLogger(DatabaseTemplateLoader.class);

	private TemplateWrap templateWrap;

	public void closeTemplateSource(Object templateSource) throws IOException 
	{
		// Do nothing
	}

	public Object findTemplateSource(String templateName) throws IOException 
	{
		try
		{
			TemplateEntity entity = templateWrap.selectByName(templateName);
			return entity;
		}
		catch (Exception e)
		{
			logger.info("Exception in findTemplateSource by name:" + templateName);
			logger.debug(e.getMessage(), e);
			return null;
		}
	}

	public long getLastModified(Object templateSource) 
	{
		if (templateSource == null) {return 0;}
		return ((TemplateEntity) templateSource).getUpdateTime().getTime();
	}

	public Reader getReader(Object templateSource, String encoding) throws IOException 
	{
		if (templateSource == null) {return null;}
		String template = ((TemplateEntity) templateSource).getContent();
		return new StringReader(template);
	}

	public TemplateWrap getTemplateWrap()
	{
		return templateWrap;
	}

	public void setTemplateWrap(TemplateWrap templateWrap)
	{
		this.templateWrap = templateWrap;
	}
}
